<template>
    <div class="gradient-content cooperateSpu full-width">
        <div :id="idName"></div>
    </div>
</template>

<script>
import DataSet from '@antv/data-set'
import { Chart } from '@antv/g2'
export default {
    props: {
        idName: {
            type: String,
            default: 'cooperateSpuChart',
        },
        chartData: {
            type: Array,
            default: () => [],
        },
        shop_id: {
            type: [String, Number],
            default: '17',
        },
    },
    watch: {
        chartData: {
            handler(val) {
                if (val.length > 0) {
                    this.$nextTick(() => {
                        if (this.height == 0) {
                            const boxContElement = document.querySelector(`.gradient-content.cooperateSpu`)
                            this.height = boxContElement.clientHeight
                        }
                        if (this.chart) {
                            this.chart.destroy()
                        }
                        this.render()
                    })
                }
            },
            immediate: true,
            deep: true,
        },
    },
    data() {
        return {
            chart: null,
            height: 0,
        }
    },
    mounted() {
        // this.$nextTick(() => {
        //     const boxContElement = document.querySelector(`.gradient-content.store`)
        //     this.height = boxContElement.clientHeight
        //     // this.render()
        // })
    },
    beforeDestroy() {
        if (!this.chart) {
            return
        }
        this.chart.destroy()
    },
    methods: {
        render() {
            // 使用传入的chartData而不是硬编码的数据
            const data = this.chartData.map(item => ({
                sku: item.sku,
                已回收: item.已回收,
                待回收: item.待回收,
            }))

            const ds = new DataSet()
            const dv = ds.createView().source(data)
            dv.transform({
                type: 'fold',
                fields: ['已回收', '待回收'], // 展开字段集
                key: '状态', // key字段
                value: '数量', // value字段
                retains: ['sku'], // 保留字段集
            })

            // 计算每个sku的总数
            const totalData = {}
            this.chartData.forEach(item => {
                totalData[item.sku] = item.已回收 + item.待回收
            })

            this.chart = new Chart({
                container: this.idName,
                height: this.height,
                autoFit: true,
                padding: [50, 10, 30, 50],
            })

            this.chart.coordinate().transpose()

            this.chart.data(dv.rows)
            this.chart.scale('数量', { nice: true })

            this.chart.axis('sku', {
                label: {
                    offset: 12,
                },
            })

            this.chart.legend({
                position: 'top',
            })
            this.chart.tooltip({
                shared: true,
                showMarkers: false,
            })

            const color = this.shop_id == 18 ? '#2db2ff' : '#8f7cff'

            this.chart.interval().adjust('stack').position('sku*数量').color('状态')

            // 移除原有的label配置，改用annotation方式添加末端标签
            // 为每个sku添加总数标签到条形图末端
            Object.keys(totalData).forEach(sku => {
                this.chart.annotation().text({
                    position: [sku, totalData[sku]],
                    content: totalData[sku].toString(),
                    style: {
                        fill: color,
                        fontSize: 12,
                        textAlign: 'left',
                    },
                    offsetX: 10,
                    offsetY: 0,
                })
            })

            this.chart.interaction('active-region')

            // Step 4: 添加点击事件
            this.chart.on('interval:click', ev => {
                console.log('ev.data', ev.data)
                const data = ev.data?.data || {}
                const seriesName = data.状态 // 获取点击柱状图的状态（已回收/待回收）
                const spu = data.sku // 获取点击的sku

                console.log(`点击了系列: ${seriesName}`, data)
                // 阻止事件冒泡到父组件
                if (ev.gEvent && ev.gEvent.originalEvent) {
                    ev.gEvent.originalEvent.stopPropagation()
                    ev.gEvent.originalEvent.preventDefault()
                }
                // 根据状态判断类型，待回收为8，已回收为9（或者相反，根据实际需求调整）
                this.$emit('barClick', {
                    type: seriesName === '待回收' ? 8 : 9,
                    spu,
                })
            })

            // Step 5: 渲染图表
            this.chart.render()
        },
    },
}
</script>
<style lang="less" scoped></style>
